<template>
  <div>
    <!--头部行表单 ：增加 -->
    <div class="filter-container">
      <el-button type="primary" :icon="DocumentAdd" @click="handleAdd">新增</el-button>
    </div>

    <!-- 数据列表 编辑 删除 -->
    <div class="list-container">
      <el-table :data="dataList" fit highlight-current-row style="width: 100%;">
        <el-table-column prop="sort" label="序号" width="55" align="center"></el-table-column>

        <el-table-column label="轮播图片" width="200" align="center">
          <template #default="{row}">
            <el-image :src="$fullUrl(row.img)"
                      :preview-src-list="[$fullUrl(row.img)]" preview-teleported ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="goodsId" label="商品id"></el-table-column>

        <el-table-column label="操作" width="180" align="center">
        	<template #default="{row}">
        		<el-button link type="primary" :icon="Edit" @click="handleUpdate(row.id)">编辑</el-button>
        		<el-button link type="danger" :icon="Delete" @click="handleDelete(row.id)">删除</el-button>
        	</template>
        </el-table-column>
      </el-table>
      <!-- 数据量不多，这里就不进行分页处理了 -->
    </div>

    <!-- 编辑弹出框 -->
    <home-carousel-edit v-if="editDialogVisible" ref="editDialogRef" @refreshDataList="loadDataList"/>
  </div>
</template>

<script setup>
import HomeCarouselEdit from './components/HomeCarouselEdit.vue';
import * as HomeAPI from '@/api/home.js';

import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { DocumentAdd, Edit, Delete } from '@element-plus/icons-vue';

const dataList = ref([]); //列表数据
const editDialogVisible = ref(false); //编辑对话框
const editDialogRef = ref(null); // 声明模板中 DOM元素的引用, 必须和模板里的 ref 同名

// 获取列表数据
const loadDataList = async () => {
	let result = await HomeAPI.getCarouselList();
	dataList.value = result.data; //返回数据结构参见API文档
};
loadDataList(); // 初始列表数据

// 删除操作
const handleDelete = id => {
	// 二次确认删除
	ElMessageBox.confirm('确定要删除吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		// 选择了确认，则删除后端数据库中的记录
		await HomeAPI.deleteById(id);
		loadDataList(); //同步列表中的记录
		ElMessage.success('删除成功');
	});
};

// 编辑操作，id为编辑记录的ID
const handleUpdate = async id => {
	editDialogVisible.value = true;
	await nextTick();
	editDialogRef.value.init(id);
};

// 增加记录
const handleAdd = async () => {
	editDialogVisible.value = true;
	await nextTick();
	editDialogRef.value.init(0); //id==0表示新增
}; 
	

</script>

<style scoped></style>
